<!-- ifram 相关 https://segmentfault.com/a/1190000016258735  https://zhuanlan.zhihu.com/p/75467242 -->
<template>
  <div  class="app-container">
    <div style="border: 1px solid; border-color: #1890ff; width:500px; height:600px;float:left">
        <ul id="treeDemo" class="ztree" @select="zTreeOnClick"></ul>
    </div>
    <div style="float:left;">
       <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item :label="$t('角色')" >
          <el-select v-model="temp.role_id" class="filter-item" placeholder="请选择角色" @change="getMenuTreeByRole" 
          filterable remote reserve-keyword clearable >
          <!-- remote-method="getRoleList"  -->
            <el-option v-for="item in roleOptions" :key="item.role_id" :label="item.role_name" :value="item.role_id" />
          </el-select>
          </el-form-item>
       </el-form>

       <div slot="footer" class="form-footer">
        <el-button type="primary" @click="saveRoleMenu()">
          {{ $t('保存') }}
        </el-button>
        
      </div>
    </div>
  </div>
</template>
<script>
import $ from 'jquery'
import "@/libs/ztree/js/jquery.ztree.core.js"
import "@/libs/ztree/js/jquery.ztree.excheck.js"
import "@/libs/ztree/css/zTreeStyle/zTreeStyle.css"
import {doSelBean,addMenu,updateMenu,deleteMenu,genCode } from '@/api/menu'
import {addRoleMenu } from '@/api/roleMenu'
import {roleList } from '@/api/role'
export default{
    data(){
        return{
            setting: {
                check: {
                    enable: true
                },
                view: {
				    selectedMulti: false
                },
                async: {
                    enable: true,
                    url: process.env.VUE_APP_BASE_API+"/menu/doSelNode?role_id="+this.$route.query.role_id+"&time="+new Date(),
                    autoParam:["id", "name=n", "level=lv"],
                    //id_ini,name_ini用于设置根结点,与当前用户所在行政区划相关. 如,哈尔滨市级用户,则使用   ,"id_ini":"230100000000","name_ini":"哈尔滨"
                    otherParam:{"otherParam":"zTreeAsyncTest","id_ini":"-1","name_ini":"xd"},
                    type:"post"
                },
               callback:{
                   onClick: this.zTreeOnClick,
                   //beforeClick: beforeClick,
                   beforeAsync: this.beforeAsync,
                   onAsyncError: this.onAsyncError,
                   onAsyncSuccess: this.onAsyncSuccess
               }
            },
            role_id :this.$route.query.role_id, //url传参
            roleOptions: [],

            type: 'update', //当前操作类型，默认为更新
            menu_code_current : '',
            menu_name_current : '',
            menu_code_readonly : true,
            menu_name_readonly : true,
            zTree : undefined,
            nodes : undefined,
            node: {
              id : 0 ,
              name : ''
            },
            zTreeOperate :'',
            temp: {
               role_id : this.$route.query.role_id,
               menu_enable:1,
               menu_img : 'user'
            },
            beanQuery: {
              menu_id: 0
            },
            genCodeParam: {
              menu_id_parent: 0,
              menu_code_parent: ''
            },
            //输入校验规则
            rules: {
                check_role_id: [{ required: true, message: '请选择角色', trigger: 'change' }]
            }
            // zNodes:[
            //     { id:"1",  pId:"0", name:"父节点1 - 展开", open:true},
			//     { id:"11", pId:"1", name:"父节点11 - 折叠"}
            // ]
        }
        
    },
    mounted(){
        //this.base_api = process.env.VUE_APP_BASE_API
        //console.log("jquery object = "+$)
        //$.fn.zTree.init($("#treeDemo"), this.setting, this.zNodes).expandAll(true);
        $.fn.zTree.init($("#treeDemo"), this.setting);
        //$("#refreshNode").bind("click", {type:"refresh", silent:false}, this.refreshNode);
		  	//$("#refreshNodeSilent").bind("click", {type:"refresh", silent:true}, this.refreshNode);
			  //$("#addNode").bind("click", {type:"add", silent:false}, this.refreshNode);
			  //$("#addNodeSilent").bind("click", {type:"add", silent:true}, this.refreshNode);
        //this.selectnode(0);
        //this.expandroot();
        this.getRoleList();
        //this.getMenuTreeByRole();
    },
    created(){
        //alet();
        if(this.$route.query.role_id != '' && this.$route.query.role_id!= null){
           this.temp.role_id = this.$route.query.role_id - 0 ;
        }
    },
    methods: {
        zTreeOnClick(event,treeId,treeNode){
            try{
              this.getMenu(treeNode.id);
            }catch(e){
              alert(e.message);
            }
        },
        beforeAsync(treeId, treeNode) {
          // className = (className === "dark" ? "":"dark");
          // showLog("[ "+getTime()+" beforeAsync ]&nbsp;&nbsp;&nbsp;&nbsp;" + ((!!treeNode && !!treeNode.name) ? treeNode.name : "root") );
          return true;
        },
        onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
          alert(textStatus);
          alert(XMLHttpRequest.status);
        },
        onAsyncSuccess(event, treeId, treeNode, msg){
          this.expandroot();
        },
        //可以全部展开菜单
        expandroot(){
          this.zTree = $.fn.zTree.getZTreeObj("treeDemo");
          this.nodes = this.zTree.getNodes();
          this.zTree.expandNode(this.nodes[0], true, false, true);
          this.nodes = this.nodes[0].children;
          if(this.nodes!=null ){
             this.zTree.expandNode(this.nodes[0], true, false, true);
             this.nodes = this.nodes[0].children;
             if(this.nodes!=null ){
                this.zTree.expandNode(this.nodes[0], true, false, true);
             }
          }
        },
        
        //this page
        getRoleList(){
            roleList({"page":1, "pageSize":10000}).then(response => {
                this.roleOptions = response.data
            })
        },
        //选择角色后，依据角色重新初始化树型组件
        getMenuTreeByRole(){
            //alert(this.temp.role_id);
            if(this.temp.role_id == null || this.temp.role_id == ''){
              return;
            }
            //alert(2);
            this.setting.async.url = process.env.VUE_APP_BASE_API+"/menu/doSelNode?role_id="+this.temp.role_id+"&time="+new Date(),
            $.fn.zTree.init($("#treeDemo"), this.setting);
        },
        getCheckedNodes(){
		       return $.fn.zTree.getZTreeObj("treeDemo").getCheckedNodes(true);
	    	},
        //保存角色的菜单配置
        saveRoleMenu() {
            if(this.temp.role_id == null || this.temp.role_id == ''){
              alert('请选择角色');
              return; 
            }
            let nodes = this.getCheckedNodes();
            let obj = new Object();
            let arr = new Array();
            for(let i=0; i<nodes.length; i++){
                    let node = nodes[i];
                    obj = new Object();
                    obj.role_id = this.temp.role_id ;
                    obj.menu_id = node.id ;
                    obj.oper = node.oper ;
                    arr.push(obj);
            }
            this.$refs['dataForm'].validate((valid) => {
              if (valid) {
                //this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
                //this.temp.author = 'vue-element-admin'
                addRoleMenu(arr).then(() => {
                  this.$notify({
                    title: '成功',
                    message: '保存成功',
                    type: 'success',
                    duration: 2000
                  })
                })
                //this.$router.push({path:'/sys/rolemenumain',query:{role_id:1}});
                //location.reload
              }
            })
        },
    }
    
}
</script>
<style lang="scss" scoped>
//用于调整form中的行间距，这个应该修改为全局变量吧！
.app-container {
  .el-form {
    .el-form-item {
      margin-bottom: 11px;
    }
  }
  .form-footer {
      margin-left: 50px;
    }
}
</style>


